window.gts || (window.gts= {
	log:window.console?function(msg){console.log(msg);}:function(msg){},//log
	getQueryValue :function (url, key) {
		var reg = new RegExp("(^|&|\\?|#)" + key + "=([^&#]*)(&|\x24|#)", "");
		var match = url.match(reg);
		if (match) {
			return match[2];
		}
		return null;
	},
	init:function(cfg){
		var me =this;
		me.config=cfg||{};
		me.language = me.getQueryValue(location.href,"lang")||"cn";
		me.i18n=me.i18n[me.language]||{};
		//初始化界面上的国际化信息
		document.title=me.i18n.title||"GPS智能监控系统";
		for(var k in me.i18n){
			var dom= document.getElementById("i18n-"+k);
			if(dom && dom.innerHTML) dom.innerHTML=me.i18n[k];
			if(dom && dom.tagName.toLowerCase()=="input") dom.value=me.i18n[k];
		}
		//加载车辆列表
		var arr=[],arrearage=0,offline=me.config.Vehicles.length,online=0;
		me.velData={};
		$.each(me.config.Vehicles,function(i,v){
			arr.push('<tr class="'+(i==0?"current":"")+'" data-SimID="'+this.SimID+'"><td align="center" valign="center"><img id="vs-'+this.SimID+'-status" src="resources/images/offline.png" /></td><td id="vs-'+this.SimID+'-VehNoF">'+this.VehNoF+'</td><td id="vs-'+this.SimID+'-DateTime">'+this.DateTime+'</td></tr>');
			me.velData[v.SimID]=v;
			me.velData[v.SimID].offline=true;
			if(v.status==2){//欠费
				offline--;
				arrearage++;
			}
		});
		$("#velList tbody").html(arr.join(""));
		$("#totalVel").html(me.config.Vehicles.length);
		$("#onlineVel").html(online);
		$("#offlineVel").html(offline);
		$("#arrearsVel").html(arrearage);

		var vehicles=[];
						

		//初始化地图
		$("#map_canvas").trigger("initmap.gts",{me:me});
		me.log("initial xmlsocket");
		//xml socket
		me.xmls = new jsXMLSocket();
		/*me.flashPlayerVersion = me.xmls.getFlashPlayerVersion();
		if(me.flashPlayerVersion < 9 && me.flashPlayerVersion !== 0){
			alert(me.config.CheckFlashPlayer||"check your flash version ,make sure above 9");
			return ;
		}*/
		me.IP=me.config.IP||"180.186.73.134";//58.60.185.172
		me.Port=me.config.Port||2000;//9800
		me.connected=false;
		me.ReCt=0;//重连次数
		me.IsProcessing=false;//在处理服务端push过来的数据
		me.DataString="";


		try {
			me.xmls.setup("#xmlsocket");
		}catch(e){ me.log("setup xmlsocket error"+e.message); }
		me.xmls.onClose = function(){
			me.log("xml socket closing");
			me.ReCt=0;
			me.connected=false;
			me.xmls.connect(me.IP,me.Port);
		};
		me.xmls.onConnect = function(success){
			me.log("xml socket conneted,success? "+success);
			me.connected = success;	
			//开始定时检测车辆在线情况
			if(success){//已经连接
				me.ReCt=0;					                                                
			}else{    
				//重连持续一分钟
				if(me.ReCt<5){    
					setTimeout(function(){
						me.log("reconnectiong..."+me.ReCt+" at "+me.IP+":"+me.Port);
						me.xmls.connect(me.IP,me.Port);
					},200);
					me.ReCt++;
				}else{//连接失败
					if(confirm(me.i18n.RefreshConfirm||"连接失败，重新连接？"))
						window.location.href=window.location.href;
				}                  
			}
		};
		me.xmls.onData = function(src) {
			me.log("recieved data:"+(src.length>50?(src.substring(0,50)+"..."):src));
			if(src!=""){
				me.DataString+=src.toString();
				if(!me.IsProcessing){
					me.IsProcessing=true;
					me.ProcessEveryJson();
				}
			}
		};
		me.xmls.onXML = function(src){};   
		me.xmls.onReady= function(){
			if(!me.connected){
				setTimeout(function(){
					me.log("connectiong... at "+me.IP+":"+me.Port);
					me.xmls.connect(me.IP,me.Port);
				},2000);
			}
		}
		 //刷新或关闭页面后断开连接
		window.onunload=function(){
			me.reset();
			if(me.connected && me.ClientID) {
				me.sendData("{\"ClientID\":\""+me.ClientID+"\",\"KillMe\":\"1\"}");
				me.xmls.close();
			}
		}

		//velList current vel change
		$("#velList").delegate("tbody tr","click",function(e){
			if(!$(this).hasClass("current")){
				$("#velList .current").removeClass("current");
				$(this).addClass("current");
				$("#velinfo [id^=vs-]").html("");
			}
			var selVel=$(this).attr("data-SimID");
			if(selVel){
				if(selVel && me.velData[selVel]){
					for(var k in me.velData[selVel]){
						var domId="vs-"+k;
						(document.getElementById(domId)) && (document.getElementById(domId).innerHTML=me.velData[selVel][k]||"");
					}
				}
				$("#map_canvas").trigger("focusvel.gts",{vel:selVel,me:me});
			}
		});
	},
	sendData:function(data){
		var me=this;
		me.log("sending data:"+data);
		me.xmls.send(data);
	},
	//处理请求回来的数据
	ProcessEveryJson:function(){
        var me=this,strs=me.DataString.split('#'),Length=strs.length;
        for(var index=0;index<Length;index++){
            if(!strs[index])  continue;
            try{
                var data=eval("("+strs[index]+")");
                me.DataString=me.DataString.replace(strs[index]+"#","");
                //me.log("processing data:"+strs[index]);
                //收到客户编号
                if(data.ServerDist) {
                    me.ClientID=data.ClientID;//记录ClientID
                    //做些准备工作：
					me.sendData("init");
					setTimeout(function(){
						me.sendData('{"ClientID":"'+me.ClientID+'","LanguageType":"'+me.i18n.langname+'"}');
					},500);
					setTimeout(function(){
						var vehicles=[];
						$.each(me.config.Vehicles,function(i,v){
							vehicles.push(v.SimID);
						});
						me.sendData('{"ClientID":"'+me.ClientID+'","AllSystemNos":"'+vehicles.join("|")+'|1","SysLength":"121"}');
					},1000);
					
                    //开始链路维持，每60秒一次，同时检查哪些车辆已经离线
                    me.maintainer && clearInterval(me.maintainer);
                    me.maintainer=setInterval(function(){
						me.sendData("{\"ClientID\":\""+me.ClientID+"\",\"MaintainLink\":\"1\"}");
						me.updateVelStatus();
					},60000);					                                                           
                }else if(data.SignalType){ //收到车机数据，而且所有车辆的系统编号均已发送完毕
                    switch(data.SignalType){
                        //报警数据处理
                        case "Alarm":
							me.log("alarm(TODO):"+data);
                            break;
                        //定位数据处理
                        case "Locate": 
							me.log("locate: "+data.SimID);
							(!me.velData) && (me.velData={});
							(!me.velData[data.SimID]) && (me.velData[data.SimID]={offline:true});
							//数据更新
							$.extend(me.velData[data.SimID],data);
							var curvelData =me.velData[data.SimID];
							if(curvelData.LocateStatus=="Locate"){//最后一次定位的时间
								curvelData.lastLocate=(new Date()).getTime();
								curvelData.offline=false;//标记为上线	
							}
							me.updateVelStatus();
							//更新左边车辆列表数据
							for(var k in curvelData){
								var domId="vs-"+data.SimID+"-"+k;
								(document.getElementById(domId)) && (document.getElementById(domId).innerHTML=curvelData[k]);
							}
							document.getElementById("vs-"+data.SimID+"-status").setAttribute("src","resources/images/online.png");
							var selVel=$("#velList .current").attr("data-SimID");
							
							//如果是更新当前选中车辆，更新底部数据信息
							if(selVel==data.SimID){
								if(selVel && me.velData[selVel]){
									for(var k in me.velData[selVel]){
										var domId="vs-"+k;
										(document.getElementById(domId)) && (document.getElementById(domId).innerHTML=me.velData[selVel][k]||"");
										
									}
									
								}
							}
							//将车辆显示在地图视口中
							$("#map_canvas").trigger("mergeview.gts",{vel:data.SimID,me:me});
							
                            break;
                        //收到车机短信
                        case "92":
							me.log("msg(TODO)/92:"+data);
                            break;
                        //拍照完毕
                        case "0C":
							me.log("0C(TODO):"+data);
                            break;
                        //指令发送后的车机回应处理，格式：{SimID:SIM卡号,ResultMsg:消息,Time:时间,SignalType:指令类型}
                        default:
                            /*var ifr=document.getElementById("ifrCMessage").contentWindow;
                            ifr.AddCMsg.call(ifr,data,"FromMachine"); 
                            //显示所有即时消息，并给予流水提示                
                            $("#tbIM").val("["+GetVehNoF(data.SimID)+"]"+data.ResultMsg);  
                            SpotText();*/
							me.log("im(TODO)"+data);
                            break;
                    }
                }
            }catch(e){
				me.log("Processing data error:"+e.message);
			}
        }
        strs=null;
        if(me.DataString)
            setTimeout(function(){me.ProcessEveryJson()},150);
        else
            me.IsProcessing=false;
	},
	updateVelStatus:function(){
		var me =this;
		//判断离线的依据：距离上次定位超过sessionTimeout视为离线，默认为30分钟
		for(SimID in (me.velData||{})){
			var vel = me.velData[SimID];
			if((!vel.lastLocate) || ( vel.lastLocate && ((new Date()).getTime()-vel.lastLocate>(me.config.sessionTimeout||1800000)))){
				document.getElementById("vs-"+SimID+"-status").setAttribute("src","resources/images/offline.png");
				if(!vel.offline){
					me.log("offline:"+SimID);
					$("#map_canvas").trigger("veloffline.gts",{vel:SimID,me:me});
				}
				//标记为离线
				vel.offline=true;
				
			}
		}
		var total = parseInt($("#totalVel").html(),10)-parseInt($("#arrearsVel").html(),10),offline=0;
		for(SimID in (me.velData||{})){
			if(me.velData[SimID].offline!==false && me.velData[SimID].status==1) offline++;
		}
		$("#onlineVel").html(total-offline);
		$("#offlineVel").html(offline);
	},
	reset:function(fn){//trigger or bind data 
		gts.log("reset");
		if(typeof(fn)=="function"){
			$("#map_canvas").bind("reset.gts",fn);
		}else{
			$("#map_canvas").trigger("reset.gts",{me:this});
		}
	}
});